package com.taoz.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taoz.usercenter.constant.UserConstant;
import com.taoz.usercenter.exception.BusinessError;
import com.taoz.usercenter.exception.BusinessException;
import com.taoz.usercenter.mapper.UserMapper;
import com.taoz.usercenter.model.domain.User;
import com.taoz.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户服务实现类
 *
 * @author taoz
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    // 密码加盐
    private static final String SALT = "taoz";

    @Override
    public Long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 用户名密码非空，且满足对应长度要求
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(BusinessError.EXIST_EMPTY_PARAMS);
        }
        if (userAccount.length() < 4 || userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(BusinessError.PARAMS_LENGTH_INVALID);
        }

        // 两次密码需要一致
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(BusinessError.REGISTER_PASSWORD_NOT_SAME);
        }

        // 账号不能包含特殊字符
        String validPattern = "[^a-zA-Z0-9_.]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(BusinessError.USER_ACCOUNT_EXIST_INVALID_CHARACTER);
        }

        // 用户名不能已被占用
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        if (this.count(queryWrapper) > 0) {
            throw new BusinessException(BusinessError.USER_ACCOUNT_IS_OCCUPIED);
        }

        // 密码加密
        userPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        // 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(userPassword);
        boolean save = this.save(user);

        if (!save) {
            throw new BusinessException(BusinessError.SAVE_NEW_USER_FAILED);
        }

        // 返回用户id
        System.out.println(user.getId());
        return user.getId();
    }

    public void makeUserInsensitive(User user) {
        user.setUserPassword("");
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest httpServletRequest) {
        // 用户名密码非空，且满足对应长度要求
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(BusinessError.EXIST_EMPTY_PARAMS);
        }
        if (userAccount.length() < 4 || userPassword.length() < 8) {
            throw new BusinessException(BusinessError.PARAMS_LENGTH_INVALID);
        }

        // 密码加密
        userPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        // 判断用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", userPassword);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            log.info("user login failed, userAccount or userPassword is not correct!");
            log.info("userAccount: " + userAccount + " userPassword: " + userPassword);
            throw new BusinessException(BusinessError.SEARCH_USER_FAILED);
        }

        // 用户存在，进行用户脱敏，并记录session
        makeUserInsensitive(user);

        HttpSession session = httpServletRequest.getSession();
        session.setAttribute(UserConstant.USER_LOGIN_STATE, user);

        return user;
    }

    @Override
    public void logout(HttpServletRequest request) {
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
    }
}




